package com.ziyun.erp.modules.member.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ziyun.erp.modules.member.dao.ConfigBaseSettingDao;
import com.ziyun.erp.modules.member.entity.ConfigBaseSettingEntity;
import com.ziyun.erp.modules.member.service.ConfigBaseSettingService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("configBaseSettingService")
public class ConfigBaseSettingServiceImpl extends ServiceImpl<ConfigBaseSettingDao, ConfigBaseSettingEntity> implements ConfigBaseSettingService {

    @Autowired
    private ConfigBaseSettingDao configBaseSettingDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<ConfigBaseSettingEntity> page = this.selectPage(
                new Query<ConfigBaseSettingEntity>(params).getPage(),
                new EntityWrapper<ConfigBaseSettingEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R info(String key) {
        if ("license".equals(key)) {
            key = "b2c.register.setting_member_license";
        } else {
            key = "b2c.register.setting_member_privacy";
        }
        ConfigBaseSettingEntity entity = selectBaseSetting(key);
        return R.ok().put("text", entity.getValue());
    }

    @Override
    public Map<String, Object> updateBaseSetting(String key, String text) {
        if ("license".equals(key)) {
            key = "b2c.register.setting_member_license";
        } else {
            key = "b2c.register.setting_member_privacy";
        }
        Map<String, Object> map = new HashMap<String, Object>();
        int res = this.update(key, text);
        if (res == 1) {
            map.put("code", 1);
            map.put("msg", "修改成功！");
        } else {
            map.put("code", 0);
            map.put("msg", "修改失败！");
        }
        return map;
    }

    private ConfigBaseSettingEntity selectBaseSetting(String key) {
        ConfigBaseSettingEntity entity = new ConfigBaseSettingEntity();
        entity.setKeyName(key);
        ConfigBaseSettingEntity result = this.configBaseSettingDao.selectOne(entity);
        return result;
    }

    private int update(String key, String text) {
        ConfigBaseSettingEntity entity = new ConfigBaseSettingEntity();
        entity.setValue(text);
        Integer result = configBaseSettingDao.update(entity, new EntityWrapper<ConfigBaseSettingEntity>().eq("key_name", key));
        return result;
    }

}
